package jobs;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

import models.Mail;
import play.Logger;
import play.Play;
import play.jobs.Job;

public class BatchMailSender extends Job {

	private Mail mail;
	private String replyTo;
	private String[] senderAccounts,senderPwds;
	/**
	 * 每个账号最多可以发送的邮件数
	 */
	private int maxPerAcount;
	
	public BatchMailSender(Mail mail){
		if(mail==null){
			throw new RuntimeException("mail is null");
		}
		this.mail = mail;
		
		String batchMailAccounts = Play.configuration.getProperty("batchMail.accounts");
		String bathcMailPwds = Play.configuration.getProperty("batchMail.accountPwd");
		
		senderAccounts = batchMailAccounts.split(",");
		senderPwds = bathcMailPwds.split(",");
		replyTo = Play.configuration.getProperty("bathcMail.replyTo");
		maxPerAcount = NumberUtils.toInt(Play.configuration.getProperty("batchMail.maxPerAccount"));
		
		Logger.debug("sender accounts: %s", senderAccounts.toString());
		Logger.debug("reply to: %s", replyTo);
		Logger.debug("maxPerAccount:", maxPerAcount);
	}
	
	@Override
	public void doJob() throws Exception {
		String[] receivers = mail.receivers.split("\\n");
		String emailPattern = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
		Pattern pattern = Pattern.compile(emailPattern);
		
		int senderIndex = 0;
		int sentAmount = 0;
		for (String receiver : receivers) {
			receiver = StringUtils.trimToEmpty(receiver);
			Matcher matcher = pattern.matcher(receiver);
			if(!matcher.matches()){
				Logger.error("邮件地址格式不正确: %s", receiver);
			}else{
				if(sentAmount==maxPerAcount){
					senderIndex++;
					sentAmount=0;
				}
				try{
					sendMail(senderAccounts[senderIndex],senderPwds[senderIndex],receiver,mail.title,mail.content);
					sentAmount++;
				}catch (Exception e) {
					Logger.error(e, "邮件发送失败，接收人: %s,主题: %s", receiver, mail.title);
				}
			}
		}
	}

	/**
	 * 发送一封邮件
	 * @param senderAccount
	 * @param senderPwd
	 * @param receiver
	 * @param title
	 * @param content
	 * @throws EmailException 
	 */
	private void sendMail(String senderAccount, String senderPwd, String receiver,
			String title, String content) throws EmailException {
		Logger.debug("发送邮件,发送账号:%s,接收人:%s,主题:%s", senderAccount,receiver,title);
		SimpleEmail email = new SimpleEmail();
		email.setSmtpPort(587);
		email.setAuthenticator(new DefaultAuthenticator(senderAccount, senderPwd));
		email.setDebug(true);
		email.setHostName("smtp.gmail.com");
		email.getMailSession().getProperties().put("mail.smtps.auth", "true");
		email.getMailSession().getProperties().put("mail.debug", "true");
		email.getMailSession().getProperties().put("mail.smtps.port", "587");
		email.getMailSession().getProperties().put("mail.smtps.socketFactory.port", "587");
		email.getMailSession().getProperties().put("mail.smtps.socketFactory.class",   "javax.net.ssl.SSLSocketFactory");
		email.getMailSession().getProperties().put("mail.smtps.socketFactory.fallback", "false");
		email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
		email.setFrom(senderAccount,"Spark Dental Store News Letter");
		email.addReplyTo(replyTo);
		email.setSubject(title);
		email.setMsg(content);
		email.addTo(receiver);
		email.setTLS(true);
		email.send();
		Logger.debug("发送完成");
	}
}
